<?php

/**
 * +----------------------------------------------------------------------
 * | TickyPHP [ This is a freeware ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2015 All rights reserved.
 * +----------------------------------------------------------------------
 * | Author: 罗敏贵 <e-mail:minguiluo@163.com> <QQ:271391233>
 * +----------------------------------------------------------------------
 * | SVN: $Id: Authrole.php 74258 2018-09-20 15:56:54 luomingui $
 * +----------------------------------------------------------------------
 * | 文件功能：对应的表名:tky_auth_role
 * +----------------------------------------------------------------------
 */

namespace application\admin\controller;

use ticky\request;
use ticky\response;
use ticky\tree;

class role extends base {

    //首页
    public function index() {
        $search = $this->search_frm();
        $ret = db('auth_role')->where($search['sql'])->order('roleid desc')->newpage();
        $this->assign('page', $ret['page']);
        $this->assign('items', $ret['items']);
        $this->assign('search', $search['arr']);
        $this->display('role/index');
    }

    // 批量删除
    public function batchremove() {
        $optype = request::post('optype', '');
        $ids = request::post('ids', []);
        if ($optype == "del") {
            db('auth_role')->delete('roleid in(' . implode(",", $ids) . ')');
            showmsg('删除成功', '/admin/role');
        } else {
            if (is_array($_GET['title'])) {
                foreach ($_GET['title'] as $id => $val) {
                    $data = array();
                    $data['title'] = $_GET['title'][$id];
                    db('auth_role')->update($data, ['roleid' => $id]);
                }
            }
            if (is_array($_GET['newtitle'])) {
                foreach ($_GET['newtitle'] as $key => $value) {
                    if ($value) {
                        $data = array();
                        $data['title'] = $value;
                        $data['status'] = 1;
                        $data['rules'] = '';
                        db('auth_role')->where(['roleid' => $id])->insert($data);
                    }
                }
            }
            showmsg('更新成功', '/admin/role');
        }
    }

    //查询条件
    private function search_frm() {
        $search = request::get('search', []);
        $where = '1=1 ';
        if ($roleid = trim($search['roleid'])) {
            $where .= "and roleid = '{$roleid}' ";
        }
        if ($title = trim($search['title'])) {
            $where .= "and title = '{$title}' ";
        }
        if ($status = trim($search['status'])) {
            $where .= "and status = '{$status}' ";
        }
        if ($rules = trim($search['rules'])) {
            $where .= "and rules = '{$rules}' ";
        }
        return [
            'arr' => $search,
            'sql' => $where
        ];
    }

    //权限 role/perm/?id=
    public function perm() {
        if (request::isPost()) {
            $id = request::post('roleid', 0);
            $ids = request::post('ids', []);
            $data = array();
            $data['rules'] = implode(",", $ids);
            db('auth_role')->where(['roleid' => $id])->update($data);
            showmsg('权限设置成功', '/admin/role');
        } else {
            $id = request::get('id', 0);
            $role = db('auth_role')->where('roleid=' . $id)->find();

            $html = $this->getAllRolePerm($id);
            $this->assign('title', $role['title'] . '权限');
            $this->assign('role', $role);
            $this->assign('premhtml', $html);
            $this->display('role/perm');
        }
    }

    private function getAllRolePerm($roleid) {
        $role = db('auth_role')->where('roleid=' . $roleid)->find();
        $role_rulearr = explode(",", $role['rules']);
        $checkedall = false;
        $htable = "";
        $modules = db()->query("select  DISTINCT module from tky_auth_rule where module LIKE '%admin-%'");
        foreach ($modules as $module) {
            $topkey = $module['module'];
            $labModuleArr = explode("-", $topkey);
            $labModule = $labModuleArr[count($labModuleArr) - 1];
            $showModule = L($labModule);
            $row = "<tr>
            <th class = 'text-right w-150px'>" . $showModule . "<input type = 'checkbox' name = 'allchecker[]' onclick = \"selectAll(this,'$topkey', 'checkbox')\"  " . ($checkedall ? ' checked' : '') . "/></th>
            <td id = '" . $topkey . "' class = 'pv-10px'>";
            $methods = db()->query("SELECT * FROM tky_auth_rule WHERE module='" . $module['module'] . "'");
            $chk = 0;
            for ($i = 0; $i < count($methods); $i++) {
                $method = $methods[$i];
                $fun = $method['name'];
                $labfunArr = explode("-", $fun);
                $labfun = end($labfunArr);
                $showfun = L($labfun);
                $checked = in_array($method['ruleid'], $role_rulearr) ? "checked" : "";
                if ($checked) {
                    $chk++;
                }
                $row .= "<div class = 'group-item'>
                       <input type = 'checkbox' name = 'actions[" . $topkey . "][]' value = '" . $method['ruleid'] . "' " . ($checked ? ' checked' : '') . " />
                       <span class = 'priv' id = '" . $fun . "'>" . $showfun . "</span>
                   </div>";
            }
            if ($chk == count($methods)) {
                $checkedall = true;
            }
            $row .= '</td></tr>';
            $htable .= $row;
        }
        return $htable;
    }

    //菜单权限
    public function role_priv() {
        if (request::isPost()) {
            if (is_array($_POST['menuid']) && count($_POST['menuid']) > 0) {
                db('auth_role_priv')->delete(array('roleid' => $_POST['roleid']));
                $menuinfo = db('menu')->field('`id`,`m`,`c`,`a`,`data`')->select();
                foreach ($menuinfo as $_v) {
                    $menu_info[$_v['id']] = $_v;
                }
                foreach ($_POST['menuid'] as $menuid) {
                    $info = array();
                    $info = $menu_info[$menuid];
                    if ($info['m'] == '')
                        continue;
                    $info['roleid'] = $_POST['roleid'];
                    db('auth_role_priv')->insert($info, false, false);
                }
            } else {
                db('auth_role_priv')->delete(array('roleid' => $_POST['roleid']));
            }
            cache('menu_string_' . $_POST['roleid'], null);
            showmsg(L('operation_success'));
        } else {
            $roleid = request::get('id', '0');
            $role = db('auth_role')->where('roleid=' . $roleid)->find();
            $tree = new tree();
            $tree->icon = array('│ ', '├─ ', '└─ ');
            $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
            $data = db('menu')->order('listorder ASC,id DESC')->select();

            $priv_data = db('auth_role_priv')->where(array('roleid' => $roleid))->select();
            foreach ($data as $k => $v) {
                $data[$k]['level'] = $this->get_level($v['id'], $data);
                $data[$k]['checked'] = ($this->is_checked($v, $roleid, $priv_data)) ? ' checked' : '';
            }

            $str = "<tr>
						<td><label>\$spacer<input type='checkbox' name='menuid[]' value='\$id' level='\$level' \$checked onclick='javascript:checknode(this);'> \$name</label></td>
					</tr>";
            $tree->init($data);
            $menus = $tree->get_tree(0, $str);
            $this->assign('title', $role['title'] . '权限');
            $this->assign('roleid', $roleid);
            $this->assign('role', $role);
            $this->assign('menus', $menus);
            $this->display('role/role_priv');
        }
    }

    /**
     * 获取菜单深度
     * @param $id
     * @param $array
     * @param $i
     */
    private function get_level($id, $array = array(), $i = 0) {
        foreach ($array as $n => $value) {
            if ($value['id'] == $id) {
                if ($value['parentid'] == '0')
                    return $i;
                $i++;
                return $this->get_level($value['parentid'], $array, $i);
            }
        }
    }

    /**
     *  检查指定菜单是否有权限
     * @param array $data menu表中数组
     * @param int $roleid 需要检查的角色ID
     */
    private function is_checked($data, $roleid, $priv_data) {
        $priv_arr = array('m', 'c', 'a', 'data');
        if ($data['m'] == '')
            return false;
        foreach ($data as $key => $value) {
            if (!in_array($key, $priv_arr))
                unset($data[$key]);
        }
        $data['roleid'] = $roleid;
        return in_array($data, $priv_data) ? true : false;
    }

}
